package com.ruoyi.miniapp.controller.api;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.miniapp.MiniAppUser;
import com.ruoyi.common.core.domain.miniapp.dto.MiniAppUserDTO;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.MiniAppException;
import com.ruoyi.miniapp.service.IMiniAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.security.service.TokenService;

@RestController
@RequestMapping("/miniapp")
public class WxMiniAppUserController extends BaseController
{
    @Autowired
    private IMiniAppUserService miniAppUserService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取微信小程序用户信息
     * @return
     */
    @GetMapping("/getMiniAppUserInfo")
    public R getMiniAppUserInfo()
    {
        if (getLoginUser().getMiniAppUser()!=null){
            MiniAppUser miniAppUser=miniAppUserService.selectMiniAppUserById(getLoginUser().getMiniAppUser().getId());
            return R.ok(miniAppUser);
        }
        return R.ok(getLoginUser().getMiniAppUser());
    }

    /**
     * 更新微信小程序用户信息
     * @param miniAppUserDTO
     * @return
     */
    @PostMapping("/updateMiniAppUser")
    public R updateMiniAppUser(@RequestBody MiniAppUserDTO miniAppUserDTO)
    {
        miniAppUserDTO.setTel(null);
        LoginUser loginUser = getLoginUser();
        //这里防止被人恶意发包修改 通过Security获取当前的id
        miniAppUserService.updateMiniAppUser(new MiniAppUser(miniAppUserDTO,loginUser.getMiniAppUser().getId()));
        //更新缓存
        loginUser.getMiniAppUser().setNickName(miniAppUserDTO.getNickName());
        loginUser.getMiniAppUser().setSex(miniAppUserDTO.getSex());
        loginUser.getMiniAppUser().setAge(miniAppUserDTO.getAge());
        loginUser.getMiniAppUser().setHeight(miniAppUserDTO.getHeight());
        loginUser.getMiniAppUser().setWeight(miniAppUserDTO.getWeight());
        loginUser.getMiniAppUser().setAddress(miniAppUserDTO.getAddress());
        loginUser.getMiniAppUser().setTel(miniAppUserDTO.getTel());
        loginUser.getMiniAppUser().setRealName(miniAppUserDTO.getRealName());
        loginUser.getMiniAppUser().setBirthday(miniAppUserDTO.getBirthday());
        loginUser.getMiniAppUser().setAvatar(miniAppUserDTO.getAvatar());
        tokenService.setLoginUser(loginUser);
        return R.ok();
    }

    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam("avatarfile") MultipartFile file) throws MiniAppException
    {
        LoginUser loginUser = getLoginUser();
        JSONObject data = miniAppUserService.uploadAvatar(loginUser.getMiniAppUser(), file);
        return R.ok(data);
    }
}
